package com.web.position.service;

import com.web.position.entity.Position;
import com.web.position.mapper.PositionMapper;
import com.web.rate.service.RateService;
import com.web.transaction.entity.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PositionService {

	@Resource
    private PositionMapper mapper;

	@Autowired
    private RateService rateService;

	public List<Position> genPositions(Transaction t) {
		List<Position> list = new ArrayList<Position>();
		if(t.isContainHKD()) {
			handleTxnContainHKD(list, t);
		}
		if(!t.isContainHKD()) {
			handleTxnNotContainHKD(list, t);
		}
		return list;
	}

	private void handleTxnContainHKD(List<Position> list, Transaction t) {
		if(t.isWithdrawalHKD()) {
			BigDecimal sellRate = rateService.getRate(t.getDepositeCcy(), Transaction.TX_SELL).getRate();
			BigDecimal hkdEquAmt = t.getDepositedAmt().multiply(sellRate).setScale(2, RoundingMode.HALF_DOWN);
			Position sellPosition = new Position().genSellPosition(t, hkdEquAmt);
			mapper.addPosition(sellPosition);
			list.add(sellPosition);
		}

		if(t.isDepositeHKD()) {
			BigDecimal buyRate = rateService.getRate(t.getWithdrawalCcy(), Transaction.TX_BUY).getRate();
			BigDecimal hkdEquAmt = t.getWithdrawalAmt().multiply(buyRate).setScale(2, RoundingMode.HALF_DOWN);
			Position buyPosition = new Position().genBuyPosition(t, hkdEquAmt);
			mapper.addPosition(buyPosition);
			list.add(buyPosition);
		}
	}

	private void handleTxnNotContainHKD(List<Position> list, Transaction t) {
		BigDecimal buyRate = rateService.getRate(t.getWithdrawalCcy(), Transaction.TX_BUY).getRate();
		BigDecimal sellRate = rateService.getRate(t.getDepositeCcy(), Transaction.TX_SELL).getRate();

		BigDecimal buyHkdEquAmt = t.getWithdrawalAmt().multiply(buyRate).setScale(2, RoundingMode.HALF_DOWN);
		BigDecimal sellHkdEquAmt = t.getDepositedAmt().multiply(sellRate).setScale(2, RoundingMode.HALF_DOWN);

		Position buyPosition = new Position().genBuyPosition(t, buyHkdEquAmt);
		Position sellPosition = new Position().genSellPosition(t, sellHkdEquAmt);

		mapper.addPosition(buyPosition);
		mapper.addPosition(sellPosition);

		list.add(buyPosition);
		list.add(sellPosition);
	}

	public void addPosition(Position t) {
		mapper.addPosition(t);
	}

	public void amendPosition(Position t) {
		mapper.amendPosition(t);
	}

	public List<Position> getPositions(Position t) {
		return mapper.getPositions(t);
	}

	public List<Position> getPositionsByStatus(List<String> status) {
		return mapper.getPositionsByStatus(status);
	}

	public List<Map<String,String>> getPositonForIndex() {
		return mapper.getEchartsPositionData();
	}
}
